# -*- coding: utf-8 -*-
import  urllib
import  urllib2
import  cookielib
import  re
import  time
import  datetime
import  os

def auto_log_in(url_yuyue, url_jieyue, username, password):
    url_prepare = "https://webpac.uestc.edu.cn/patroninfo*chx"
    #prepare the cookie
    cookie = cookielib.CookieJar()
    mycookie = urllib2.HTTPCookieProcessor(cookie)
    #prepare post date
    postdata = urllib.urlencode({
        "code":username
        ,"pin":password
        })
    #the request
    request = urllib2.Request(url_prepare, postdata)
    #login lib 
    opener = urllib2.build_opener(mycookie)
    opener.open(request)
    #open yuyue
    yuyue_html = opener.open(url_yuyue)
    f = file(username + '.yuyue', 'w')
    f.write(yuyue_html.read())
    f.close()

    #open jieyue 
    jieyue_html = opener.open(url_jieyue)
    f = file(username+ '.jieyue', 'w')
    f.write(jieyue_html.read())
    f.close()

def handle_yuyue(name):
    return_result = 0
    file_result = file(name + '.result', 'w')
    file_result.write("*******************************Request Book****************************")
    file_result.write('\n')
    file_yuyue = open(name + '.yuyue', 'r')
    book_flag = 0
    for eachline in file_yuyue:
        if book_flag:
            line_len = len(eachline)
            line_len = line_len - 5
            book = eachline[51:line_len]
        book_flag = re.search('<td  class="patFuncTitle">', eachline)

        kequ_flag = re.search("已可取, 必须在", eachline)
        if kequ_flag:
            line_len = len(eachline)
            line_len = line_len - 6
            content = eachline[28:line_len]
            file_result.write(book)
            file_result.write("\n"+content+'\n')
            return_result = 1

    file_yuyue.close()
    file_result.close()
    return return_result


def auto_renew(username, password, renew_book_info):
    url_prepare = "https://webpac.uestc.edu.cn/patroninfo*chx"
    #prepare the cookie
    cookie = cookielib.CookieJar()
    mycookie = urllib2.HTTPCookieProcessor(cookie)
    #prepare post date
    postdata = urllib.urlencode({
        "code":username
        ,"pin":password
        })
    #the request
    request = urllib2.Request(url_prepare, postdata)
    #login lib 
    opener = urllib2.build_opener(mycookie)
    opener.open(request)

    auto_html = opener.open('https://webpac.uestc.edu.cn/patroninfo~S1*chx/1055367/items?renewsome=TRUE&' + renew_book_info)
    f = file(username+'.renew', 'w')
    f.write(auto_html.read())
    f.close()
    f = open(username+'.renew', 'r')
    for scanreasonline in f:
        failed_toosoon = re.search('TOO SOON TO RENEW', scanreasonline)
        failed_toomany = re.search('TOO MANY RENEWALS', scanreasonline)
        if failed_toosoon:
            f.close()
            return 'toosoon'
        if failed_toomany:
            f.close()
            return 'toomany' 
    f.close()
    return 'true'


def handle_jieyue(username, password, tiqian_days):
    tiqian_days = int(tiqian_days)
    return_result = 0
    file_result = file(username+'.result', 'a')
    file_result.write('\n')
    file_result.write("*******************************Soon Expire Book****************************")
    file_result.write('\n')
    file_jieyue = open(username+ '.jieyue', 'r')
    for eachline in file_jieyue:

        book_flag = re.search('<td align="left" class="patFuncTitle">', eachline)
        if book_flag:
            line_len = len(eachline)            
            line_len = line_len - 5
            book = eachline[211:line_len]
            renew_book_info = eachline[97]
            if '"' == renew_book_info:
                renew_book_info = eachline[91:97] + "=" + eachline[106:114]
            else:
                renew_book_info = eachline[91:98] + "=" + eachline[107:115]

        flag = re.search('<td align="left" class="patFuncStatus">', eachline)
        if flag:
            year = re.match('.*\d\d-.*', eachline)
            if year:
                date = eachline[47:55]
                year = '20'+date[0:2]
                month = date[3:5]
                day = date[6:8]
                duetime = time.strptime(year+month+day, "%Y%m%d")
                duetime = datetime.datetime(*duetime[0:6])
                jiange = duetime - datetime.datetime.today()
                if jiange.days < tiqian_days:
                    return_result = 1
                    file_result.write("BookName:"+book)
                    file_result.write("\nDueTime:"+str(duetime))
                    file_result.write("\t\tStillHaveTime:\t"+str(jiange.days)+" Days")
                    if jiange.days < 35:
                        renew_result = auto_renew(username, password, renew_book_info)
                        if 'true' == renew_result:
                            file_result.write("\n" + "I have help you renew this book. Don't worry\n")
                        if 'toosoon' == renew_result:
                            file_result.write("\n" + "I can't help you renew this book.")
                            file_result.write(" Reasons may be:TOO SOON TO RENEW \n")
                        if 'toomany' == renew_result:
                            file_result.write("\n" + "I can't help you renew this book.")
                            file_result.write(" Reasons may be:TOO MANY RENEWALS \n")
                    file_result.write("\n\n")

    file_jieyue.close()
    file_result.close()
    return return_result 

def send_mail(email, filename):
    str_email = 'mail -s "Library" ' + email + ' < ' + filename
    os.system(str_email)
    print "send_mail sucess"

def handle_pearson(name, password, email, url, tiqian_days):
    url_yuyue = url[0:len(url)-2]+"/holds"
    url_jieyue = url[0:len(url)-2]+"/items"
    auto_log_in(url_yuyue, url_jieyue, name, password)

    handle_yuyue_content = handle_yuyue(name)
    handle_jieyue_content = handle_jieyue(name, password, tiqian_days)
    if (handle_jieyue_content + handle_yuyue_content) > 0:
        send_mail(email, name+'.result')
    else:
        print (name+"no news to send")
    str_del_tempfile = 'rm ' + name + '.*'
    os.system(str_del_tempfile)

if __name__ == "__main__":
    user_info = open('userinfo', 'r')
    recyle = 0
    for eachline in user_info:
        if (recyle % 5) == 0:
            name = eachline
        if (recyle % 5) == 1:
            password = eachline
        if (recyle % 5) == 2:
            email = eachline
        if (recyle % 5) == 3:
            url = eachline
        if (recyle % 5) == 4:
            days = eachline
            handle_pearson(name[0:len(name)-1], password[0:len(password)-1], email[0:len(email)-1], url, days[0:len(days)-1])
        recyle = recyle + 1
